import {getCategoryList,getCategory2List,getCategory3List} from "@/api/categoryList"
// 引入创建切片的方法
import {createSlice} from "@reduxjs/toolkit"
// 创建切片的方法
const categorySlice = createSlice({
  // 必须的模块名
  name:"category",
  // 初始化的数据
  initialState:{
    category1Id:'',
    category2Id:'',
    category3Id:'',
    category1List:[],
    category2List:[],
    category3List:[]
  },
  // 操作state的方法
  reducers:{
    setCategory1List(state,{payload}){
      state.category1List = payload.data
    },
    setCategory2List(state,{payload}){
      state.category2List = payload.data
    },
    setCategory3List(state,{payload}){
      state.category3List = payload.data
    }
  }
})

// 每个切片暴露 俩个东西  actions 和 reducer
export const {setCategory1List,setCategory2List,setCategory3List} = categorySlice.actions
// 暴露reducer
export default categorySlice.reducer

// 获取一级分类的方法
export const getCategoryListAsync = ()=>{
  // console.log(1);
  return async(dispatch:any,getState:any)=>{
    try {
      const res = await getCategoryList()
      // console.log(res);
      dispatch(setCategory1List(res))
    } catch (error) {
      return Promise.reject("failed")
    }
  }
}

export const getCategory2ListAsync = (value:any)=>{
  // console.log(1);
  return async(dispatch:any,getState:any)=>{
    try {
      const res = await getCategory2List(value)
      // console.log(res);
      dispatch(setCategory2List(res))
    } catch (error) {
      return Promise.reject("failed")
    }
  }
}

export const getCategory3ListAsync = (value:any)=>{
  // console.log(1);
  return async(dispatch:any,getState:any)=>{
    try {
      const res = await getCategory3List(value)
      // console.log(res);
      dispatch(setCategory3List(res))
    } catch (error) {
      return Promise.reject("failed")
    }
  }
}